import cv2
import numpy as np
import qrcode
from PIL import Image
from docx import Document
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.oxml import OxmlElement

from docx.shared import Inches
from docx.oxml.ns import qn

doc = Document()  # doc对象


def set_cell_border(cell, **kwargs):
    """
    Set cell`s border
    Usage:
    set_cell_border(
        cell,
        top={"sz": 12, "val": "single", "color": "#FF0000", "space": "0"},
        bottom={"sz": 12, "color": "#00FF00", "val": "single"},
        left={"sz": 24, "val": "dashed", "shadow": "true"},
        right={"sz": 12, "val": "dashed"},
    )
    """
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

    # check for tag existnace, if none found, then create one
    tcBorders = tcPr.first_child_found_in("w:tcBorders")
    if tcBorders is None:
        tcBorders = OxmlElement('w:tcBorders')
        tcPr.append(tcBorders)

    # list over all available tags
    for edge in ('left', 'top', 'right', 'bottom', 'insideH', 'insideV'):
        edge_data = kwargs.get(edge)
        if edge_data:
            tag = 'w:{}'.format(edge)

            # check for tag existnace, if none found, then create one
            element = tcBorders.find(qn(tag))
            if element is None:
                element = OxmlElement(tag)
                tcBorders.append(element)

            # looks like order of attributes is important
            for key in ["sz", "val", "color", "space", "shadow"]:
                if key in edge_data:
                    element.set(qn('w:{}'.format(key)), str(edge_data[key]))


def welcome():
    print("请输入要生成二维码的行数：")
    row = input()
    print("请输入要生成二维码的列数：")
    column = input()
    print("两个二维码相隔的距离：")
    distance = input()
    dis = int(distance)
    col = int(column)
    r = int(row)
    num = ((r * col + 1) // 2)
    table = doc.add_table(rows=num, cols=2)
    print((r * col + 1) // 2)

    for i in range(0, r):
        for j in range(0, col):
            text = 'x=' + str(i * dis) + ',' + 'y=' + str(j * dis)
            # text = '000' + str(i+j)

            print(text)
            # 生成二维码
            img = qrcode.make(data=text)
            # # 直接显示二维码
            # img.show()
            # 保存二维码为文件
            # img=cv2.resize(1024,1024)
            img.save("qrcode.jpg")

            # 加载背景图片
            bk_img0 = cv2.imread("qrcode.jpg")
            # 在图片上添加文字信息
            bk_img0 = cv2.resize(bk_img0, (480, 480), 0, 0)

            shape_y = bk_img0.shape[0]
            shape_x = bk_img0.shape[1]

            # 逆时针旋转90度，算法工程师太懒了，吐槽死他
            matRotate = cv2.getRotationMatrix2D((shape_y * 0.5, shape_x * 0.5), 90, 1)  # 旋转变化矩阵
            bk_img0 = cv2.warpAffine(bk_img0, matRotate, (shape_x, shape_y))  # 旋转

            # 去除黑边
            bk_img0 = bk_img0[3:480, 3:480]
            bk_img0 = cv2.resize(bk_img0, (600, 600), 0, 0)

            texta = "Mobot    " + text
            # texta ='1200'+ '      840'
            cv2.putText(bk_img0, texta, (int(shape_y / 2) - 80, 40), cv2.FONT_HERSHEY_SIMPLEX,
                        1, (218, 123, 233), 4, cv2.LINE_AA)

            bk_img = np.zeros((1300, 1300, 3), np.uint8)
            # 使用白色填充图片区域,默认为黑色
            bk_img.fill(255)

            bk_img[350:950, 350:950] = bk_img0[0:600, 0:600]

            shape_y = bk_img.shape[0]
            shape_x = bk_img.shape[1]
            ptStart = (int(shape_y / 2), 0)
            ptEnd = (int(shape_y / 2), 80)
            point_color = (0, 0, 0)  # BGR
            thickness = 3
            lineType = 4
            cv2.line(bk_img, ptStart, ptEnd, point_color, thickness, lineType)

            ptStart = (int(shape_y / 2), int(shape_x) - 80)
            ptEnd = (int(shape_y / 2), int(shape_x))
            point_color = (0, 0, 0)  # BGR
            thickness = 3
            lineType = 4
            cv2.line(bk_img, ptStart, ptEnd, point_color, thickness, lineType)

            ptStart = (0, int(shape_x / 2))
            ptEnd = (80, int(shape_x / 2))
            point_color = (0, 0, 0)  # BGR
            thickness = 3
            lineType = 4
            cv2.line(bk_img, ptStart, ptEnd, point_color, thickness, lineType)

            ptStart = (int(shape_y) - 80, int(shape_x / 2))
            ptEnd = (int(shape_y), int(shape_x / 2))
            point_color = (0, 0, 0)  # BGR
            thickness = 3
            lineType = 4
            cv2.line(bk_img, ptStart, ptEnd, point_color, thickness, lineType)
            # bk_img = cv2.bitwise_not(bk_img)
            cv2.resize(bk_img, (480, 480))

            # 保存图片
            cv2.imwrite("%d_%d.jpg" % (i * dis, j * dis), bk_img)
            icon = Image.open('1.png')

            # 保存图片
            bk_img = Image.open("%d_%d.jpg" % (i * dis, j * dis))
            assert isinstance(bk_img, Image.Image)
            # 参数设置logo的大小
            factor = 8
            size_w = int(shape_y / factor)
            size_h = int(shape_x / factor)
            icon_w, icon_h = icon.size
            if icon_w > size_w:
                icon_w = size_w
            if icon_h > size_h:
                icon_h = size_h
            # 重新设置logo的尺寸
            icon = icon.resize((icon_w, icon_h), Image.ANTIALIAS)

            # 得到画图的x，y坐标，居中显示
            w = int((shape_y - icon_w) / 2)
            h = int((shape_x - icon_h) / 2)
            # 黏贴logo照
            bk_img.paste(icon, (w, h), mask=None)
            bk_img.save("%d_%d.jpg" % (i * dis, j * dis))

            bk_img = cv2.imread("%d_%d.jpg" % (i * dis, j * dis))
            cv2.circle(bk_img, (int(shape_x / 2), int(shape_y / 2)), 4, (0, 0, 0), 8)
            cv2.imwrite("%d_%d.jpg" % (i * dis, j * dis), bk_img)

            # doc.add_paragraph("                           "
            #                   "          ")  # 添加文字
            if (i * col + j + 1) % 2 == 1:
                count1 = int((i * col + j + 1) / 2)
                cell = table.cell(count1, 0)
                print(count1, 0)
                p = cell.paragraphs[-1]
                cell.paragraphs[-1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 水平 居中
                cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER  # 垂直 居中
                run = p.add_run()
                run.add_picture("%d_%d.jpg" % (i * dis, j * dis), height=Inches(2.2))
                # set_cell_border(cell,
                #                 top={"sz": 24, "val": "single", "color": "FFFFFF", "space": "0"},
                #                 bottom={"sz": 12, "color": "FFFFFF", "val": "single"},
                #                 left={"sz": 12, "val": "dashed", "color": "FFFFFF", "shadow": "true"},
                #                 right={"sz": 10, "color": "FFFFFF", "val": "dashed"},
                #                 insideH={"color": "FFFFFF"}, )
                set_cell_border(cell,
                                top={"sz": 5, "val": "single", "color": "000000", "space": "0"},
                                bottom={"sz": 5, "color": "000000", "val": "single","space": "0"},
                                left={"sz": 5, "val": "single", "color": "000000", "shadow": "true","space": "0"},
                                right={"sz": 5, "color": "000000", "val": "single","space": "0"},
                                insideH={"sz": 5,"color": "000000","val": "single"}, )

            else:
                count2 = int(((i * col + j + 1) / 2) - 1)
                cell = table.cell(count2, 1)
                print(count2, 1)
                p = cell.paragraphs[-1]
                cell.paragraphs[-1].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER  # 水平 居中
                cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER  # 垂直 居中
                run = p.add_run()
                run.add_picture("%d_%d.jpg" % (i * dis, j * dis), height=Inches(2.2))
                # set_cell_border(cell,
                #                 top={"sz": 24, "val": "single", "color": "FFFFFF", "space": "0"},
                #                 bottom={"sz": 12, "color": "FFFFFF", "val": "single"},
                #                 left={"sz": 24, "val": "dashed", "color": "FFFFFF", "shadow": "true"},
                #                 right={"sz": 10, "color": "FFFFFF", "val": "dashed"},
                #                 insideH={"color": "FFFFFF"}, )
                set_cell_border(cell,
                                top={"sz": 5, "val": "single", "color": "000000", "space": "0"},
                                bottom={"sz": 5, "color": "000000", "val": "single","space": "0"},
                                left={"sz": 5, "val": "single", "color": "000000", "shadow": "true","space": "0"},
                                right={"sz": 5, "color": "000000", "val": "single","space": "0"},
                                insideH={"sz": 5,"color": "000000","val": "single"}, )

                # doc.add_picture("%d_%d.jpg" % (i, j), width=Inches(2.00))

    doc.save('1.docx')


if __name__ == '__main__':
    welcome()
